package org.graduation.ical.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.graduation.ical.mapper.UserAndICSKeyMapper;
import org.graduation.ical.service.UserAndICSKeyService;
import org.graduation.model.common.ics.UserAndICSKey;
import org.graduation.utils.Encrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class UserAndICSKeyServiceImpl extends ServiceImpl<UserAndICSKeyMapper, UserAndICSKey> implements UserAndICSKeyService {
    private Random random = new Random();
    @Autowired
    private Encrypt encrypt;
    @Autowired
    private UserAndICSKeyMapper userAndICSKeyMapper;


    protected String randomKey(Integer uid) {
        // 根据uid、当前时间戳、随机数生成一个32位的字符串
        int randomNumber = random.nextInt(Integer.MAX_VALUE);
        String randomStr = String.valueOf(uid) + System.currentTimeMillis() + randomNumber;
        return encrypt.md5_32(randomStr);
    }

    @Override
    public String resetKey(Integer uid) {
        String randomStr = randomKey(uid);
        UserAndICSKey userAndICSKey = userAndICSKeyMapper.selectById(uid);
        if(userAndICSKey == null){
            userAndICSKey = new UserAndICSKey(uid,randomStr);
            userAndICSKeyMapper.insert(userAndICSKey);
        }else{
            userAndICSKey.setIcsKey(randomStr);
            userAndICSKeyMapper.updateById(userAndICSKey);
        }
        return randomStr;
    }
}
